import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, message, Modal, Select, Tree, TreeSelect, DatePicker, Checkbox, Tabs, InputNumber } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, getYear, getPayCycleDom, getStringByType, getNameByState, confirmDelete, renderExt } from 'lib/fun'
import FilterModule from './filterCitizenLitter'
import EditSuccessCitizen from './editSuccessCitizen'

const TreeNode = Tree.TreeNode;
const Option = Select.Option;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

const findRowDataProject = function(data, id){
  var find = false;
  _.each(data, (item)=>{
    var f = _.find(item.children, (i)=>{
      return i.projectId == id
    })
    if(f){
      find = f
    }
  });
  return find
}

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      visible: false,
      rowdata: {},
      see: false
    }
    this.current = 1;   //当前第几页
    this.total = 0;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};

    this.isEdit = false;
  }

  componentDidMount(){
    const { config, addConfig } = this.props;
    if(!config.genderCode){
      // 性别
      addConfig('genderCode', 7);
    }
    if(!config.bankCode){
      // 所属银行
      addConfig('bankCode', 31);
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
      this.current = 1;   //当前第几页
      this.total = 10;   //总共多少页
      this.pageSize = 10;

      this.search = {};
      
      this.isEdit = false;
    }else if(!this.props.visible){
      // nextProps.batchId&&(nextProps.batchId != this.props.batchId||nextProps.type != this.props.type||!this.props.batchId)
      this.loadData(nextProps);
    }
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadData = (props) => {
    var self = this;
    self.setState({
      loading: true
    });
    const { identNumber, name, uploadId } = this.search;
    const { type, batchId, isSummary } = props?props:this.props;
    var url = getStringByType('url', type);
    if(url){
      Ajax({
        url: url,
        data: {
          identNumber,
          name,
          uploadId,
          currentPage: self.current,  //请求页码
          perPage: self.pageSize,   //每页数量
          batchId: isSummary?undefined:batchId,
          summaryId: isSummary?batchId:undefined
        },
        success: function(data){
          self.total = data.totalCount;
          self.setState({
            loading: false,
            data: data.list
          });
        },
        error: function(error){
          self.setState({
            loading: false
          });
          message.error(error);
        }
      });
    }
  }

  handleFilter = (option)=>{
    if(!_.isEqual(option, this.search)){
      this.search = option;
      this.loadData();
    }
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onClose(this.isEdit);
  }

  operate = (row, see)=>{
    this.setState({
      visible: true,
      rowdata: row,
      see: see?true:false
    });
  }

  editOk = (rowdata)=>{
    var self = this;
    var find = _.find(self.state.data, (item)=>{
      return item.registerId == rowdata.registerId
    })
    Object.assign(find, rowdata);
    self.setState({
      visible: false,
      data: self.state.data
    });
    this.isEdit = true
  }
  editCancel = ()=>{
    this.setState({
      visible: false
    });
  }
  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/projectRegister/deleteCitizen',
        data: {
          "registerIds": [id]
        },
        success: function(data){
          // _.remove(self.state.data, function(d) {
          //   return d.registerId == id
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
          self.isEdit = true;
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除');
    });
  }

  renderPeople = ()=>{
    var self = this;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 18 },
      wrapperCol: { span: 6 },
    };
    const { visible, type, batchId, isSummary, failDown, successDown } = this.props;
    const { bankCode } = this.props.config;

    const { config, common, see } = this.props;
    const columns = [{
      title: '用户姓名',
      dataIndex: 'name'
    }, {
      title: '证件号码',
      dataIndex: 'identNumber'
    }];
    if(type != 'rFail'){
      columns.push({
        title: '性别',
        dataIndex: 'genderCode',
        render: (text, record) => (<span>{ getNameByCode(config, 'genderCode', text) }</span>)
      }, {
        title: '开户银行',
        dataIndex: 'bankCode',
        render: (text, record) => (<span>{ getNameByCode(config, 'bankCode', text) }</span>)
      }, {
        title: '银行卡号',
        dataIndex: 'bankNumber'
      }, {
        title: '用户归属区划',
        dataIndex: 'areaName'
      }, {
        title: '金额',
        dataIndex: 'subsidyMoney'
      }, {
        title: '扩展属性',
        dataIndex: 'projectExtensionDetailList',
        render: (text, record) => (<span>{ renderExt(text) }</span>)
      }, {
        title: '状态',
        dataIndex: 'state',
        render: (text, record) => (<span>{ getNameByState(common, "projectRegisterEn", text) }</span>)
      });
    }else{
      columns.push({
        title: '开户银行',
        dataIndex: 'bankName'
      }, {
        title: '银行卡号',
        dataIndex: 'bankNumber'
      }, {
        title: '时间',
        dataIndex: 'createTime'
      }, {
        title: '金额',
        dataIndex: 'subsidyMoney'
      }, {
        title: '扩展属性',
        dataIndex: 'projectExtensionDetailList',
        render: (text, record) => (<span>{ renderExt(text) }</span>)
      });
    }
    columns.push({
      title: '失败原因',
      dataIndex: 'failReason'
    })
    if(type != 'rFail'){
      if(see){
        columns.push({
          title: '操作',
          key: 'action',
          render: (text, record) => (<span><a onClick={this.operate.bind(this, record, true)} href="javascript:;">查看</a></span>)
        });
      }else{
        columns.push({
          title: '操作',
          key: 'action',
          render: (text, record) => (<span><a onClick={this.operate.bind(this, record, false)} href="javascript:;">编辑</a> | <a onClick={this.doDelete.bind(this, record.registerId)} href="javascript:;">删除</a></span>)
        });
      }
    }

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    return (
      <div>
        <FilterModule 
          handleFilter={ this.handleFilter }
          type={type}
          batchId={batchId}
          isSummary={isSummary}
          visible={visible}
          failDown={failDown}
          successDown={successDown}
        />
        <div style={{marginTop: 15}}>
          <Table 
            columns={columns}
            loading={this.state.loading}
            dataSource={ this.state.data }
            rowKey="registerId"
            pagination={ pagination }
          />
        </div>
      </div>
    )
  }

  render() {
    const { visible, type } = this.props;
    
    return (<div>
              <Modal 
                title={ getStringByType('title', type) }
                visible={visible}
                onOk={ this.onCancel } 
                onCancel={ this.onCancel }
                okText="确定"
                cancelText="取消"
                width="1100px"
              >
                { this.renderPeople() }
              </Modal>
              <EditSuccessCitizen
                visible={this.state.visible}
                rowdata={this.state.rowdata}
                onCancel={()=>{
                  this.setState({
                    visible: false
                  });
                }}
                onSuccess={this.editOk}
                see={this.state.see}
                type={type}
              />
            </div>
            );
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common,
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(Form.create()(ModuleName))